package spynx.desl.runtime.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import spynx.desl.runtime.IExecutionContext;
import spynx.desl.runtime.IObjectVariable;
import spynx.desl.runtime.IVariable;
import spynx.util.DeslUtil;

public class ExecutionContext extends AbstractExecutionContext {

	public ExecutionContext(IExecutionContext parent) {
		super(parent);
	}

	protected Map<String, List<IVariable>> objects = new HashMap<String, List<IVariable>>();
	
	public static IExecutionContext createRootContext() {
		ExecutionContext context = new ExecutionContext(null);
		context.Variables().addVariable(new Variable("console", System.out));
		context.Variables().addVariable(new Variable("String", String.class));
		context.Variables().addVariable(new Variable("DeslUtil", DeslUtil.class));
		return context;
	}
	
	@Override
 	public IObjectVariable createObjectVariable(String name, String className) {
		List<IVariable> list = objects.get(name);
		if (list == null) 
			objects.put(className, list = new ArrayList<IVariable>());
		ObjectVariable var = new ObjectVariable(className);
		var.setName(name);
		vars.addVariable(var);
		list.add(var);
		return var;
	}

	@Override
	public void clearContext() {
		super.clearContext();
		for(Object key: objects.keySet().toArray()) {
			if (((String)key).startsWith(".")) {
				objects.remove(key);
			}
		}
	}

	@Override
	public IExecutionContext createChildContext() {
		return new ExecutionContext(this);
	}
}
